package com.hd.trans.utils;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.StrictMode;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.hd.trans.files.model.FileSortModel;

import java.io.File;


/**
 * Created by yc on 2019/8/11.
 */
public class SharedFileUtils {
    private static SharedFileUtils instance;
    private static String fileName = "trans";

    public static SharedFileUtils getInstance(Context context) {
        if (instance == null) {
            synchronized (SharedFileUtils.class) {
                if (instance == null) {
                    instance = new SharedFileUtils();
                }
            }
        }

        return instance;
    }



    /**
     * 存储排序方式
     *
     * @param modeItem
     */
    public void putFileSortModeItem(FileSortModel.ModeItem modeItem) {
//        putObject("ModeItem", modeItem);
    }

    /**
     * 获取排序方式
     *
     * @return
     */
    public FileSortModel.ModeItem getFileSortModeItem() {
//        return getObject("ModeItem", FileSortModel.ModeItem.class);
        return null;
    }


    /**
     * 分享拍照翻译的文本
     *
     * @param activity 分享需要传入一个activity
     * @param outPath  分享的文件
     */
    public static void shareFile(Context activity, String outPath) {
        /*PermissionHelper.INSTANCE.requestStorage(activity, new Function0<Unit>() {
            @Override
            public Unit invoke() {
                try {
                    if (!checkFile(activity, outPath)) {
                        return null;
                    }
                    StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
                    StrictMode.setVmPolicy(builder.build());
                    Intent intent = new Intent(Intent.ACTION_SEND);
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    intent.putExtra(Intent.EXTRA_STREAM, getShareUri(activity, new File(outPath)));
                    String mimeType=getMimeTypeFromPath(new File(outPath));
                    intent.setType(mimeType);
                    activity.startActivity(Intent.createChooser(intent, "分享到"));
                } catch (ActivityNotFoundException e) {
                    e.printStackTrace();
                }
                return null;
            }
        }, new Function0<Unit>() {
            @Override
            public Unit invoke() {
                return null;
            }
        },false);*/

        try {
            if (!checkFile(activity, outPath)) {
                return;
            }
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.putExtra(Intent.EXTRA_STREAM, getShareUri(activity, new File(outPath)));
            String mimeType=getMimeTypeFromPath(new File(outPath));
            intent.setType(mimeType);
            activity.startActivity(Intent.createChooser(intent, "分享到"));
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }

    }


    public static String getMimeTypeFromPath(File f) {
//        FileNameMap fileNameMap = URLConnection.getFileNameMap();
//        return fileNameMap.getContentTypeFor(f.getName());
        String ext = getExtension(f.getAbsolutePath());
        return MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext.replace(".",""));
    }

    public static String  getExtension(String uri) {
        if (uri == null) {
            return "";
        }
        int dot = uri.lastIndexOf(".");
        if (dot >= 0) {
            return uri.substring(dot + 1);
        }
        return "";
    }

    private static boolean checkFile(Context activity, String outPath) {
        if (TextUtils.isEmpty(outPath)) {
            ToastUtils.showNormal("文件不存在");
            return false;
        }
        File outFile = new File(outPath);
        if (!outFile.exists()) {
            ToastUtils.showNormal("文件不存在");
            return false;
        }
        return true;
    }


    public static Uri getShareUri(Context activity, File file) {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            return FileProvider.getUriForFile(activity, activity.getPackageName() + ".FileProvider", file);
        } else {
            return Uri.fromFile(file);
        }

    }

    /** 分享到微信 */
    public static void shareToWeChat(Activity activity, String path) {
        //判断是否安装微信，如果没有安装微信 又没有判断就直达微信分享是会挂掉的
        if (!isAppInstall(activity, "com.tencent.mm")) {
            ToastUtils.showNormal( "您还没有安装微信");
            return;
        }
        if (!checkFile(activity,path)){
            return;
        }
        File file = new File(path);
        Intent intent = getShareIntent(activity,file);
        intent.setComponent(new ComponentName("com.tencent.mm","com.tencent.mm.ui.tools.ShareImgUI"));
        activity.startActivity(intent);
    }

    /** 分享图片给QQ */
    public static void shareToQQ(Activity activity, String path) {
        if (!isAppInstall(activity, "com.tencent.mobileqq")) {
            ToastUtils.showNormal("您还没有安装QQ");
            return;
        }
        if (!checkFile(activity,path)){
            return;
        }
        File file = new File(path);
        Intent intent = getShareIntent(activity,file);
        intent.setComponent(new ComponentName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity"));
        activity.startActivity(Intent.createChooser(intent, "shareImageToQQFriend"));
    }

    private static Intent getShareIntent(Activity activity,File file){
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.putExtra(Intent.EXTRA_STREAM, getShareUri(activity,file));
        intent.setType("*/*");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION|Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        return intent;
    }

    /**
     * 方法一
     * 检测是否安装有某个应用
     * @param context
     * @return true-安装，false-未安装
     */
    public static boolean isAppInstall(Context context, String packageName) {
        PackageManager packageManager = context.getPackageManager();
        boolean hasInstallWx;
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(packageName,PackageManager.GET_GIDS);
            hasInstallWx = packageInfo != null;
        } catch (PackageManager.NameNotFoundException e) {
            hasInstallWx = false;
            e.printStackTrace();
        }
        return hasInstallWx;
    }

    /**
     * 方法二
     * 检测是否安装有某个应用
     */
    private static boolean isAppInstall(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }


    /**
     * 根据应用包名，跳转到应用市场
     * @param activity    承载跳转的Activity
     */
    public static void shareAppShop(Context activity) {
        try {
            Uri uri = Uri.parse("market://details?id="+ activity.getPackageName());
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            if (intent.resolveActivity(activity.getPackageManager()) != null){//判断是否可以相应
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                activity.startActivity(intent);
            }else {
                ToastUtils.showNormal("您没有安装应用市场");
            }
        } catch (Exception e) {
            ToastUtils.showNormal("您没有安装应用市场");
        }
    }
}

